import { toolchain } from "../../toolchain.js";
import { BaseTask, TaskResult } from "./BastTask.js";
import fg from "fast-glob";
import path from "path";
import { EFileErrorType, alertErrorFile, emphasize, sendBuildFailureAlert } from "../../tools/alert.js";

export class CheckFileNameTask extends BaseTask {
    async run(): Promise<TaskResult<void>> {
        if (toolchain.option.platform == 'WebGL') {
            const assetsRoot = path.join(toolchain.params.workSpacePath, 'Assets');
            const images = await fg(['**/*.png', '**/*.jpg', '**/*.tga'], { cwd: assetsRoot });
            const repeatDots: string[] = [], illegalTokens: string[] = [], hans: string[] = [];
            for (const img of images) {
                if (img.includes('..')) {
                    // 小游戏贴图文件如果包含多余的.会导致加载失败
                    repeatDots.push(img);
                } else if (img.includes('images/sprite') || img.includes('ui/texture')) {
                    // 非图集图片文件名不允许有空格和中文，否则会加载失败
                    if (img.includes(' ')) {
                        illegalTokens.push(img);
                    } else if (img.search(/[\u4e00-\u9fa5]+/) >= 0) {
                        hans.push(img);
                    }
                }
            }
            const msgs: string[] = [];
            let errorFile = '', fileStr = '';
            if (repeatDots.length > 0) {
                fileStr = repeatDots.map(v => path.basename(v)).join(', ');
                msgs.push(emphasize(`多余的.(${repeatDots.length})`) + `: ${fileStr}`);
                errorFile = repeatDots[0];
            }
            if (illegalTokens.length > 0) {
                fileStr = illegalTokens.map(v => path.basename(v)).join(', ');
                msgs.push(emphasize(`包含空格(${illegalTokens.length})`) + `: ${fileStr}`);
                errorFile = illegalTokens[0];
            }
            if (hans.length > 0) {
                fileStr = hans.map(v => path.basename(v)).join(', ');
                msgs.push(emphasize(`包含中文(${hans.length})`) + `: ${fileStr}`);
                errorFile = hans[0];
            }
            if (msgs.length > 0) {
                await alertErrorFile(path.join(assetsRoot, errorFile), EFileErrorType.FileNameError, fileStr);
                await sendBuildFailureAlert('以下资源命名错误：' + msgs.join('\n'));
                process.exit(1);
            }
        }

        return { success: true, errorCode: 0 };
    }
}
